//
//  KYCustomCheckInView.m
//  KYKJPackDemo
//
//  Created by Jordan zhou on 2017/10/17.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "KYCustomCheckInView.h"
#import "KYCustomCheckInButton.h"
#import "KYCustomCheckInFooterView.h"
#import "KYCustomCheckInShowView.h"
#import "KYCacheManager.h"
#import "KYCalendarCellItem.h"
#import "KYServer.h"
#import "KYCheckInPrizeModel.h"
#import "KYCheckInOverallDataModel.h"

@interface KYCustomCheckInView()<KYCustomCheckInButtonDelegate>
@property (nonatomic, weak) UIImageView *bgImgView;
@property (nonatomic, weak) KYCustomCheckInButton *checkInBtn;
@property (nonatomic, weak) UIButton *checkDetailBtn;
@property (nonatomic, weak) UILabel *tipsLabel;
@property (nonatomic, weak) KYCustomCheckInFooterView *footer;
@end

@implementation KYCustomCheckInView

+ (instancetype)customCheckInView {
    return [[self alloc] init];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUpSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        [self setUpSubViews];
    }
    
    return self;
}

- (void)setUpSubViews
{
    self.backgroundColor = KYColor(212, 59, 51, 1);

    // 1.添加签到按钮
    KYCustomCheckInButton *checkInBtn = [KYCustomCheckInButton customCheckInButton];
    checkInBtn.delegate = self;
    [self addSubview:checkInBtn];
    self.checkInBtn = checkInBtn;
     //2.添加签到详情
    UIButton *checkDetailBtn = [[UIButton alloc] init];
    checkDetailBtn.layer.cornerRadius = 18;
    checkDetailBtn.layer.masksToBounds = YES;
    checkDetailBtn.backgroundColor = KYColor(255, 129, 44, 1.0);
    [checkDetailBtn setTitle:NSLocalizedString(@"签到详情", nil) forState:UIControlStateNormal];
    [checkDetailBtn setTitle:NSLocalizedString(@"点击收起", nil) forState:UIControlStateSelected];
    [checkDetailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    checkDetailBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17.0f];
    [checkDetailBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
    checkDetailBtn.tag = KYCustomCheckInDetailBtn;
    [self addSubview:checkDetailBtn];
    self.checkDetailBtn = checkDetailBtn;

    //3.累计签到天数
    UILabel *tipsLabel = [[UILabel alloc] init];
    KYCalendarCellItem *item = [KYCalendarCellItem currentDayCacheModel];
    if (item) {
        tipsLabel.text = [NSString stringWithFormat:@"连续签到%ld天",item.continuityTime];
    }else{
        tipsLabel.text = NSLocalizedString(@"连续签到0天", nil);
    }
    tipsLabel.font = [UIFont systemFontOfSize:12];
    tipsLabel.textColor = [UIColor whiteColor];
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:tipsLabel];
    self.tipsLabel = tipsLabel;
    
    //4.签到天数标志
    KYCustomCheckInFooterView *footer = [KYCustomCheckInFooterView customCheckInFooterView];
    [self addSubview:footer];
    self.footer = footer;
    
    // 5.设置底部背景图
    UIImageView *bgImgView = [[UIImageView alloc] init];
    [self addSubview:bgImgView];
    self.bgImgView = bgImgView;
    self.bgImgView.frame = CGRectMake(20, 220, kScreenWidth-40, 30);
    self.bgImgView.image = [UIImage ky_imageNamed:@"CheckIn_bgImage"];
    [self setUpBaseData];
}
- (void)setUpBaseData{
    KYCacheManager *cacheMgr = [KYCacheManager shareInstance];
    NSString *CheckDataCacheKey = [NSString stringWithFormat:@"KYPrize%@",[NSDate currentDayString]];
    if ([cacheMgr ky_isContainObjectForKey:CheckDataCacheKey]) {
        KYCheckInOverallDataModel *model = (KYCheckInOverallDataModel *)[cacheMgr ky_ObjectForKey:CheckDataCacheKey];
        [self updateDrawNumber:model.retainDrawNumber];
    }else{
        [self.footer updateTipslabel:@"请签到"];
    }
}
#pragma mark - method
- (void)btnClick:(UIButton *)btn
{
    if (btn.tag == KYCustomCheckInDetailBtn ) {
        btn.selected = !btn.selected;
    }
    if ([self.delegate respondsToSelector:@selector(customCheckInView:didClickBtnWithType: ButtonStatus:)]) {
        [self.delegate customCheckInView:self didClickBtnWithType:btn.tag ButtonStatus:[btn isSelected]];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    //签到按钮
    CGFloat checkInBtnX = self.frame.size.width * 0.5;
    CGFloat checkInBtnY = self.frame.size.height * 0.3;
    CGFloat checkInBtnW = 105;
    CGFloat checkInBtnH = checkInBtnW;
    self.checkInBtn.center = CGPointMake(checkInBtnX, checkInBtnY);
    self.checkInBtn.bounds = CGRectMake(0, 0, checkInBtnW, checkInBtnH);
    
    //签到详情
    CGFloat checkDetailBtnW = 110;
    CGFloat checkDetailBtnX = self.frame.size.width - checkDetailBtnW + 15;
    CGFloat checkDetailBtnY = 10;
    CGFloat checkDetailBtnH = 35;
    self.checkDetailBtn.frame = CGRectMake(checkDetailBtnX, checkDetailBtnY, checkDetailBtnW, checkDetailBtnH);
    
    //底部的条
    CGFloat footerX = 30;
    CGFloat footerY = CGRectGetMaxY(self.checkInBtn.frame) + 30;
    CGFloat footerW = self.frame.size.width-60;
    CGFloat footerH = 40;
    self.footer.frame = CGRectMake(footerX, footerY, footerW, footerH);
    
    //签到天数
    CGFloat tipsLabelX = self.checkInBtn.ky_centerX;
    CGFloat tipsLabelH = 30;
    CGFloat tipsLabelY = CGRectGetMaxY(self.footer.frame) + tipsLabelH * 0.5 + 8;
    CGFloat tipsLabelW = 195;
    self.tipsLabel.center = CGPointMake(tipsLabelX, tipsLabelY);
    self.tipsLabel.bounds = CGRectMake(0, 0, tipsLabelW, tipsLabelH);
   
}

#pragma mark - KYCustomCheckInButtonDelegate
- (void)customCheckInButtonView:(KYCustomCheckInButton *)checkInButtonView didClickCheckInBtn:(UIButton *)checkInBtn
{
    //点击签到按钮后先判断有没有签到过，如果已经签到什么也不做
    //没有签到的话，发送网络请求获取最新的数据
    if (![checkInBtn.titleLabel.text isEqualToString:@"已签到"]) {
        [checkInBtn setTitle:@"已签到" forState:UIControlStateNormal];
        checkInBtn.enabled = NO;
        
        KYCacheManager *cacheMgr = [KYCacheManager shareInstance];
        
        // 1.2存储签到信息
        NSDate *date = [NSDate date];
        NSDate *lastDayDate = [NSDate lastDay:date];
        //获取前一天的数据
        NSString *lastDayCheckKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",[NSDate year:lastDayDate],[NSDate month:lastDayDate],[NSDate day:lastDayDate]];
        NSInteger originTime = 0;;
        BOOL iscontain = [cacheMgr ky_isContainObjectForKey:lastDayCheckKey];
        if (iscontain) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:lastDayCheckKey];
            originTime = item.continuityTime;
            KYCalendarCellItem *itemNew = [KYCalendarCellItem calendarCellItemWithIconType:CoinEnable isHighLight:YES year:[NSDate year:date] month:[NSDate month:date] day:[NSDate day:date] continuityTime:originTime+1];
            NSString *checkKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",[NSDate year:date],[NSDate month:date],[NSDate day:date]];
            [cacheMgr ky_setObject:itemNew forKey:checkKey];
            [self requestCheckInInfoWithSignDay:[NSString stringWithFormat:@"%ld",originTime+1]];
        }else{
            KYCalendarCellItem *itemNew = [KYCalendarCellItem calendarCellItemWithIconType:CoinEnable isHighLight:YES year:[NSDate year:date] month:[NSDate month:date] day:[NSDate day:date] continuityTime:1];
            NSString *checkKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",[NSDate year:date],[NSDate month:date],[NSDate day:date]];
            [cacheMgr ky_setObject:itemNew forKey:checkKey];
            [self requestCheckInInfoWithSignDay:@"1"];
        }
    }
}

- (void)requestCheckInInfoWithSignDay:(NSString *)signDay{
    [KYServer requsetPrizeDrawData:signDay success:^(NSDictionary *dataDict) {
        NSArray *arr = dataDict[@"data"];
        NSMutableArray *arrM = [NSMutableArray array];
        for (NSInteger i = 0; i < 8; i ++) {
            NSDictionary *dic = arr[i];
            KYCheckInPrizeModel *model = [KYCheckInPrizeModel checkInPrizeModelWithDict:dic modelIndex:i];
            [arrM addObject:model];
        }
        KYCheckInOverallDataModel *overallDataModel = [KYCheckInOverallDataModel checkInOverallDataModelWithDict:dataDict];
        //更新抽奖数据列表
        if ([self.delegate respondsToSelector:@selector(refreshPrizeDrawWithDataArray:overallPrizeDrawModel:)]) {
            [self.delegate refreshPrizeDrawWithDataArray:[arrM copy] overallPrizeDrawModel:overallDataModel];
        }
        //更新机会次数
        [self updateDrawNumber:overallDataModel.signNum.integerValue];
        //将网络数据缓存
        KYCacheManager *cacheMgr = [KYCacheManager shareInstance];
        [cacheMgr ky_setObject:arrM forKey:KYPrizeData];
        [cacheMgr ky_setObject:overallDataModel forKey:KYPrizeOverallData];
        [cacheMgr ky_setObject:overallDataModel forKey:[NSString stringWithFormat:@"KYPrize%@",[NSDate currentDayString]]];
    } failure:nil];
}
- (void)updateDrawNumber:(NSInteger)time{
    if (time <= 0) {
        [self.footer updateTipslabel:[NSString stringWithFormat:@"机会已用完"]];
    }else{
        [self.footer updateTipslabel:[NSString stringWithFormat:@"%ld次机会",time]];
    }
}
- (void)refreshFooter{
    [self.footer refreshDate];
}
@end
